<template>
  <a-modal
    :open="open"
    :title="task ? $t('tasks.actions.edit') : $t('tasks.create')"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="loading"
    width="700px"
    :maskClosable="false"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item :label="$t('tasks.columns.name')" name="name">
            <a-input
              v-model:value="formState.name"
              :placeholder="$t('tasks.form.nameRequired')"
              allow-clear
            />
          </a-form-item>
        </a-col>
        
        <a-col :span="12">
          <a-form-item :label="$t('tasks.form.repeatType')" name="repeatType">
            <a-select
              v-model:value="formState.repeatType"
              :placeholder="$t('tasks.form.repeatTypePlaceholder')"
              @change="handleRepeatTypeChange"
            >
              <a-select-option value="once">{{ $t('tasks.form.once') }}</a-select-option>
              <a-select-option value="daily">{{ $t('tasks.form.daily') }}</a-select-option>
              <a-select-option value="weekly">{{ $t('tasks.form.weekly') }}</a-select-option>
              <a-select-option value="monthly">{{ $t('tasks.form.monthly') }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <!-- 执行时间设置 -->
      <a-row :gutter="16">
        <template v-if="formState.repeatType === 'once'">
          <a-col :span="12">
            <a-form-item :label="$t('tasks.form.executeDate')" name="date">
              <a-date-picker
                v-model:value="formState.date"
                style="width: 100%"
                :disabledDate="disabledDate"
              />
            </a-form-item>
          </a-col>
        </template>
        
        <template v-if="formState.repeatType === 'weekly'">
          <a-col :span="24">
            <a-form-item :label="$t('tasks.form.repeatDays')" name="weekDays">
              <a-checkbox-group v-model:value="formState.weekDays">
                <a-checkbox value="1">{{ $t('tasks.form.monday') }}</a-checkbox>
                <a-checkbox value="2">{{ $t('tasks.form.tuesday') }}</a-checkbox>
                <a-checkbox value="3">{{ $t('tasks.form.wednesday') }}</a-checkbox>
                <a-checkbox value="4">{{ $t('tasks.form.thursday') }}</a-checkbox>
                <a-checkbox value="5">{{ $t('tasks.form.friday') }}</a-checkbox>
                <a-checkbox value="6">{{ $t('tasks.form.saturday') }}</a-checkbox>
                <a-checkbox value="0">{{ $t('tasks.form.sunday') }}</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </a-col>
        </template>

        <template v-if="formState.repeatType === 'monthly'">
          <a-col :span="12">
            <a-form-item :label="$t('tasks.form.monthlyDate')" name="monthDay">
              <a-select
                v-model:value="formState.monthDay"
                :placeholder="$t('tasks.form.monthlyDatePlaceholder')"
                style="width: 100%"
              >
                <a-select-option v-for="i in 31" :key="i" :value="i">
                  {{ i }}{{ $t('tasks.form.day') }}
                </a-select-option>
                <a-select-option value="-1">{{ $t('tasks.form.lastDay') }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </template>

        <a-col :span="12">
          <a-form-item :label="$t('tasks.form.executeTime')" name="time">
            <a-time-picker
              v-model:value="formState.time"
              format="HH:mm:ss"
              :show-now="false"
              style="width: 100%"
              :input-read-only="true"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item :label="$t('tasks.columns.command')" name="command">
        <a-textarea
          v-model:value="formState.command"
          :placeholder="$t('tasks.form.commandPlaceholder')"
          :auto-size="{ minRows: 3, maxRows: 6 }"
          allow-clear
        />
      </a-form-item>

      <a-form-item :label="$t('tasks.form.description')" name="description">
        <a-textarea
          v-model:value="formState.description"
          :placeholder="$t('tasks.form.descriptionPlaceholder')"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          allow-clear
        />
      </a-form-item>

      <a-form-item name="enabled">
        <a-checkbox v-model:checked="formState.enabled">
          {{ $t('tasks.form.enableSchedule') }}
        </a-checkbox>
        <div style="font-size: 12px; color: #666; margin-top: 4px;">
          {{ $t('tasks.form.enableScheduleDesc') }}
        </div>
      </a-form-item>

      <a-form-item name="executeAfterSave" v-if="!task">
        <a-checkbox v-model:checked="formState.executeAfterSave">
          {{ $t('tasks.form.executeAfterSave') }}
        </a-checkbox>
        <div style="font-size: 12px; color: #666; margin-top: 4px;">
          {{ $t('tasks.form.executeAfterSaveDesc') }}
        </div>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">{{ $t('common.cancel') }}</a-button>
        <a-button type="primary" @click="handleOk" :loading="loading">
          {{ $t('common.confirm') }}
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import dayjs, { Dayjs } from 'dayjs'
import { taskAPI } from '@/api'
import type { Task, CreateTaskData } from '@/types/task'

const { t } = useI18n()

interface FormState extends Omit<CreateTaskData, 'schedule'> {
  repeatType: 'once' | 'daily' | 'weekly' | 'monthly'
  date?: Dayjs
  time?: Dayjs
  weekDays?: string[]
  monthDay?: number
  executeAfterSave?: boolean
}

interface Props {
  open: boolean
  task?: Task
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:open', open: boolean): void
  (e: 'success', task: Task): void
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const formState = reactive<FormState>({
  name: '',
  command: '',
  repeatType: 'once',
  enabled: true,
  description: '',
  executeAfterSave: false
})

// 禁用过去的日期
const disabledDate = (current: Dayjs) => {
  return current && current < dayjs().startOf('day')
}

// 处理重复类型变化
const handleRepeatTypeChange = () => {
  // 重置相关字段
  formState.date = undefined
  formState.weekDays = []
  formState.monthDay = undefined
}

// 将界面友好的时间配置转换为 Cron 表达式
const generateCronExpression = (): string => {
  const time = formState.time
  if (!time) {
    throw new Error(t('tasks.form.timeRequired'))
  }

  const second = time.second()
  const minute = time.minute()
  const hour = time.hour()

  switch (formState.repeatType) {
    case 'once': {
      if (!formState.date) {
        throw new Error(t('tasks.form.dateRequired'))
      }
      const date = formState.date
      return `${second} ${minute} ${hour} ${date.date()} ${date.month() + 1} *`
    }
    case 'daily':
      return `${second} ${minute} ${hour} * * *`
    case 'weekly': {
      if (!formState.weekDays?.length) {
        throw new Error(t('tasks.form.weekDaysRequired'))
      }
      return `${second} ${minute} ${hour} * * ${formState.weekDays.join(',')}`
    }
    case 'monthly': {
      if (formState.monthDay === undefined) {
        throw new Error(t('tasks.form.monthDayRequired'))
      }
      const day = formState.monthDay === -1 ? 'L' : formState.monthDay
      return `${second} ${minute} ${hour} ${day} * *`
    }
    default:
      throw new Error(t('tasks.form.invalidRepeatType'))
  }
}

// 从 Cron 表达式解析为界面友好的时间配置
const parseCronExpression = (cron?: string) => {
  if (!cron) {
    // 如果没有 cron 表达式，设置默认值
    formState.repeatType = 'once'
    formState.time = dayjs().add(1, 'hour').startOf('hour') // 默认设置为下一个整点
    formState.date = dayjs().add(1, 'day') // 默认设置为明天
    return
  }

  const [second, minute, hour, dayOfMonth, month, dayOfWeek] = cron.split(' ')

  // 设置时间
  formState.time = dayjs().hour(Number(hour)).minute(Number(minute)).second(Number(second))

  if (dayOfWeek !== '*') {
    // 每周重复
    formState.repeatType = 'weekly'
    formState.weekDays = dayOfWeek.split(',')
  } else if (dayOfMonth === '*') {
    // 每天重复
    formState.repeatType = 'daily'
  } else if (dayOfMonth === 'L' || !isNaN(Number(dayOfMonth))) {
    // 每月重复
    formState.repeatType = 'monthly'
    formState.monthDay = dayOfMonth === 'L' ? -1 : Number(dayOfMonth)
  } else if (month !== '*') {
    // 仅执行一次
    formState.repeatType = 'once'
    formState.date = dayjs()
      .month(Number(month) - 1)
      .date(Number(dayOfMonth))
  }
}

// 当编辑任务时，填充表单数据
watch(
  () => props.task,
  (newTask) => {
    if (newTask) {
      // 编辑任务时，只复制表单需要的字段
      formState.name = newTask.name
      formState.command = newTask.command
      formState.enabled = newTask.enabled
      formState.description = newTask.description || ''
      formState.executeAfterSave = false
      parseCronExpression(newTask.schedule)
    } else {
      // 新建任务时重置表单
      formState.name = ''
      formState.command = ''
      formState.repeatType = 'once'
      formState.enabled = true
      formState.description = ''
      formState.executeAfterSave = false
      parseCronExpression() // 设置默认时间
    }
  },
  { immediate: true }
)

const rules = {
  name: [
    { required: true, message: t('tasks.form.nameRequired'), trigger: 'blur' },
    { max: 50, message: t('tasks.form.nameMaxLength'), trigger: 'blur' }
  ],
  command: [
    { required: true, message: t('tasks.form.commandRequired'), trigger: 'blur' },
    { max: 1000, message: t('tasks.form.commandMaxLength'), trigger: 'blur' }
  ],
  repeatType: [
    { required: true, message: t('tasks.form.repeatTypeRequired'), trigger: 'change' }
  ],
  date: [
    { 
      required: true,
      message: t('tasks.form.dateRequired'),
      trigger: 'change',
      type: 'object',
      validator: (_rule: any, value: any) => {
        if (formState.repeatType === 'once' && !value) {
          return Promise.reject(t('tasks.form.dateRequired'))
        }
        return Promise.resolve()
      }
    }
  ],
  time: [
    { required: true, message: t('tasks.form.timeRequired'), trigger: 'change', type: 'object' }
  ],
  weekDays: [
    {
      required: true,
      message: t('tasks.form.weekDaysRequired'),
      trigger: 'change',
      type: 'array',
      validator: (_rule: any, value: any) => {
        if (formState.repeatType === 'weekly' && (!value || value.length === 0)) {
          return Promise.reject(t('tasks.form.weekDaysRequired'))
        }
        return Promise.resolve()
      }
    }
  ],
  monthDay: [
    {
      required: true,
      message: t('tasks.form.monthDayRequired'),
      trigger: 'change',
      validator: (_rule: any, value: any) => {
        if (formState.repeatType === 'monthly' && value === undefined) {
          return Promise.reject(t('tasks.form.monthDayRequired'))
        }
        return Promise.resolve()
      }
    }
  ]
}

const handleOk = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true
    
    // 生成 Cron 表达式
    const schedule = generateCronExpression()
    
    // 只发送表单相关的字段
    const taskData = {
      name: formState.name,
      command: formState.command,
      enabled: formState.enabled,
      description: formState.description,
      schedule
    }
    
    let result: Task
    if (props.task) {
      result = await taskAPI.updateTask(props.task.id, taskData)
    } else {
      result = await taskAPI.createTask(taskData)
    }
    
    message.success(t('tasks.messages.saveSuccess'))
    
    // 如果是新建任务且选择了保存后立即执行
    if (!props.task && formState.executeAfterSave) {
      try {
        const executeResult = await taskAPI.executeTask(result.id)
        if (executeResult.success) {
          message.success(t('tasks.messages.executeSuccess'))
        } else {
          message.warning(t('tasks.messages.createSuccessExecuteFailed'))
        }
      } catch (executeError: any) {
        console.error('执行任务失败:', executeError)
        message.warning(t('tasks.messages.createSuccessExecuteFailed'))
      }
    }
    
    emit('success', result)
    handleCancel()
  } catch (error: any) {
    console.error('保存任务失败:', error)
    message.error(error.message || error.response?.data?.msg || t('common.error'))
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  formRef.value?.resetFields()
  emit('update:open', false)
}
</script>

<style lang="less" scoped>
.item-content {
  display: flex;
}

:deep(.ant-form-item-label) {
  padding-bottom: 4px;
}

:deep(.ant-input-group-wrapper) {
  width: 100%;
}

:deep(.ant-checkbox-group) {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}
</style> 